package org.jeecg.modules.demo.summary.controller;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.net.URLDecoder;
import javax.el.ELException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.knife4j.core.util.CommonUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.electriccharge.entity.ElectricCharge;
import org.jeecg.modules.demo.electriccharge.service.IElectricChargeService;
import org.jeecg.modules.demo.flowable.model.ProcessStatusEntity;
import org.jeecg.modules.demo.flowable.model.TaskInstanceEntity;
import org.jeecg.modules.demo.flowable.service.IProcessMethods;
import org.jeecg.modules.demo.monthlyitem.entity.MonthlySummaryItem;
import org.jeecg.modules.demo.monthlyitem.service.IMonthlySummaryItemService;
import org.jeecg.modules.demo.prerecharge.entity.PreRecharge;
import org.jeecg.modules.demo.prerecharge.service.IPreRechargeService;
import org.jeecg.modules.demo.shenhe.entity.HywyReportProcessApproveRecord;
import org.jeecg.modules.demo.shenhe.service.IHywyReportProcessApproveRecordService;
import org.jeecg.modules.demo.summary.entity.MonthlySummary;
import org.jeecg.modules.demo.summary.mapper.MonthlySummaryMapper;
import org.jeecg.modules.demo.summary.service.IMonthlySummaryService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.service.impl.SysRoleServiceImpl;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 月度汇总报表
 * @Author: jeecg-boot
 * @Date:   2024-04-02
 * @Version: V1.0
 */
@Api(tags="月度汇总报表")
@RestController
@RequestMapping("/summary/monthlySummary")
@Slf4j
public class MonthlySummaryController extends JeecgController<MonthlySummary, IMonthlySummaryService> {
	@Autowired
	private IMonthlySummaryService monthlySummaryService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IMonthlySummaryItemService monthlySummaryItemService;

	@GetMapping(value = "/queryUserById")
	public Result<SysUser> queryUserById(@RequestParam(name = "id", required = true) String id) {
	 Result<SysUser> result = new Result<SysUser>();
	 SysUser sysUser = sysUserService.getById(id);
	 if (sysUser == null) {
		 result.error500("未找到对应实体");
	 } else {
		 result.setResult(sysUser);
		 result.setSuccess(true);
	 }
	 return result;
	}

	/**
	 * 分页列表查询
	 *
	 * @param monthlySummary
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "月度汇总报表-分页列表查询")
	@ApiOperation(value="月度汇总报表-分页列表查询", notes="月度汇总报表-分页列表查询")
	@PermissionData(pageComponent = "summary/MonthlySummaryList")
	@GetMapping(value = "/list")
	public Result<IPage<MonthlySummary>> queryPageList(MonthlySummary monthlySummary,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MonthlySummary> queryWrapper = QueryGenerator.initQueryWrapper(monthlySummary, req.getParameterMap());
		Page<MonthlySummary> page = new Page<MonthlySummary>(pageNo, pageSize);
		IPage<MonthlySummary> pageList = monthlySummaryService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	@Autowired
	private ISysDictItemService sysDictItemService;
	 /**
	  * 代办工作项查询
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/flowable/process/list")
	 public Result<List<TaskInstanceEntity>> processFlowableList(HttpServletRequest req,
																 @RequestParam(name = "page", defaultValue = "1") int page) {

		 //获取登录用户的ID
		 LoginUser user= (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<Task> someoneOngoingTasks = processMethods.getSomeoneOngoingTasks(user.getId());
		 List<TaskInstanceEntity> taskInstanceEntityList = new ArrayList<>();
		 int y = 1;
		 for (int i = 0; i < someoneOngoingTasks.size(); i++) {
			 TaskInstanceEntity taskInstanceEntity = new TaskInstanceEntity();
			 //设置流程实例ID
			 taskInstanceEntity.setProcessInstanceId(someoneOngoingTasks.get(i).getProcessInstanceId());
			 //设置时间
			 taskInstanceEntity.setStartTime(someoneOngoingTasks.get(i).getCreateTime());
			 //设置任务名称
			 QueryWrapper<MonthlySummary> monthlySummaryQueryWrapper = new QueryWrapper<>();
			 monthlySummaryQueryWrapper.eq("act_process_id",someoneOngoingTasks.get(i).getProcessInstanceId());
			 List<MonthlySummary> list = monthlySummaryService.list(monthlySummaryQueryWrapper);
			 if (CollectionUtil.isEmpty(list)){
				 continue;
			 }
			 if (list.size()>0){
				 //操作
				 taskInstanceEntity.setCaozuo("办理");
				 taskInstanceEntity.setXuhao(y);
				 //设置报表名称
				 taskInstanceEntity.setItemName(list.get(0).getReportName());
				 //设置报表ID
				 taskInstanceEntity.setId(list.get(0).getId());
				 //设置阶段名称
				 String progress = list.get(0).getProgress();
				 QueryWrapper<SysDictItem> sysDictItemQueryWrapper = new QueryWrapper<>();
				 sysDictItemQueryWrapper.eq("dict_id","1774975226050961410").eq("item_value",progress);
				 List<SysDictItem> list1 = sysDictItemService.list(sysDictItemQueryWrapper);
				 taskInstanceEntity.setName(list1.get(0).getItemText());
				 //设置状态
				 taskInstanceEntity.setProgress(list.get(0).getProgress());
				 taskInstanceEntityList.add(taskInstanceEntity);
				 y++;
			 }
		 }
		 if (page == 4){
			 List<TaskInstanceEntity> firstFourElements = taskInstanceEntityList.subList(0, Math.min(taskInstanceEntityList.size(), 4));
			 return Result.OK(firstFourElements);
		 }
		 return Result.OK(taskInstanceEntityList);
	 }

	 /**
	  * 已办工作项查询
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/flowable/process/yibanlist")
	 public Result<List<TaskInstanceEntity>> processFlowableYibanList(HttpServletRequest req,
																	  @RequestParam(name = "page", defaultValue = "1") int page) {
		 //获取登录用户的ID
		 LoginUser user= (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<HistoricTaskInstance> someoneOngoingTasks = processMethods.getSomeoneProcessingCompleted(user.getId());
		 List<TaskInstanceEntity> taskInstanceEntityList = new ArrayList<>();
		 int y = 1;
		 for (int i = 0; i < someoneOngoingTasks.size(); i++) {
			 TaskInstanceEntity taskInstanceEntity = new TaskInstanceEntity();
			 //设置流程实例ID
			 taskInstanceEntity.setProcessInstanceId(someoneOngoingTasks.get(i).getProcessInstanceId());
			 //设置阶段名称
			 taskInstanceEntity.setName(someoneOngoingTasks.get(i).getName());
			 //设置时间
			 taskInstanceEntity.setStartTime(someoneOngoingTasks.get(i).getCreateTime());
			 //设置任务名称
			 QueryWrapper<MonthlySummary> monthlySummaryQueryWrapper = new QueryWrapper<>();
			 monthlySummaryQueryWrapper.eq("act_process_id",someoneOngoingTasks.get(i).getProcessInstanceId());
			 List<MonthlySummary> list = monthlySummaryService.list(monthlySummaryQueryWrapper);
			 if (CollectionUtil.isEmpty(list)){
				 continue;
			 }
			 if (CollectionUtil.isNotEmpty(list)){
				 //操作
				 taskInstanceEntity.setCaozuo("查看");
				 taskInstanceEntity.setXuhao(y);
				 //设置报表名称
				 taskInstanceEntity.setItemName(list.get(0).getReportName());
				 //设置报表ID
				 taskInstanceEntity.setId(list.get(0).getId());
				 //设置阶段名称
				 String progress = list.get(0).getProgress();
				 QueryWrapper<SysDictItem> sysDictItemQueryWrapper = new QueryWrapper<>();
				 sysDictItemQueryWrapper.eq("dict_id","1774975226050961410").eq("item_value",progress);
				 List<SysDictItem> list1 = sysDictItemService.list(sysDictItemQueryWrapper);
				 taskInstanceEntity.setName(list1.get(0).getItemText());
				 //设置状态
				 taskInstanceEntity.setProgress(list.get(0).getProgress());
				 taskInstanceEntityList.add(taskInstanceEntity);
			 }
			 y++;
		 }
		 if (page == 4){
			 List<TaskInstanceEntity> firstFourElements = taskInstanceEntityList.subList(0, Math.min(taskInstanceEntityList.size(), 4));
			 return Result.OK(firstFourElements);
		 }
		 return Result.OK(taskInstanceEntityList);
	 }

	 /**
	  * 获取我发起的
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/flowable/process/faqiofme")
//	 @RequiresPermissions("user:faqiofme")
	 public Result<List<TaskInstanceEntity>> processFlowableFaqiOfMeList(HttpServletRequest req,
																		 @RequestParam(name = "page", defaultValue = "1") int page) {
		 //获取登录用户的ID
		 LoginUser user= (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 SysRole roleOfUser = monthlySummaryService.getRoleOfUser(user.getId());
		 if (!roleOfUser.getRoleCode().equals("wuyezuanyuan")){
			 return Result.OK("");
		 }
		 List<HistoricTaskInstance> someoneOngoingTasks = processMethods.getSomeoneProcessInitiated(user.getId());
		 List<TaskInstanceEntity> taskInstanceEntityList = new ArrayList<>();
		 int y = 1;
		 for (int i = 0; i < someoneOngoingTasks.size(); i++) {
			 TaskInstanceEntity taskInstanceEntity = new TaskInstanceEntity();
			 //设置流程实例ID
			 taskInstanceEntity.setProcessInstanceId(someoneOngoingTasks.get(i).getProcessInstanceId());
			 //设置阶段名称
			 taskInstanceEntity.setName(someoneOngoingTasks.get(i).getName());
			 //设置时间
			 taskInstanceEntity.setStartTime(someoneOngoingTasks.get(i).getCreateTime());
			 taskInstanceEntity.setCaozuo("查看");
//			 taskInstanceEntity.setXuhao(i+1);
			 //设置任务名称
			 QueryWrapper<MonthlySummary> monthlySummaryQueryWrapper = new QueryWrapper<>();
			 monthlySummaryQueryWrapper.eq("act_process_id",someoneOngoingTasks.get(i).getProcessInstanceId());
			 List<MonthlySummary> list = monthlySummaryService.list(monthlySummaryQueryWrapper);
			 if (CollectionUtil.isEmpty(list)){
				 continue;
			 }
			 if (CollectionUtil.isNotEmpty(list)){
				 //操作
				 taskInstanceEntity.setCaozuo("查看");
				 taskInstanceEntity.setXuhao(y);
				 //设置报表名称
				 taskInstanceEntity.setItemName(list.get(0).getReportName());
				 //设置报表ID
				 taskInstanceEntity.setId(list.get(0).getId());
				 //设置阶段名称
				 String progress = list.get(0).getProgress();
				 QueryWrapper<SysDictItem> sysDictItemQueryWrapper = new QueryWrapper<>();
				 sysDictItemQueryWrapper.eq("dict_id","1774975226050961410").eq("item_value",progress);
				 List<SysDictItem> list1 = sysDictItemService.list(sysDictItemQueryWrapper);
				 taskInstanceEntity.setName(list1.get(0).getItemText());
				 //设置状态
				 taskInstanceEntity.setProgress(list.get(0).getProgress());
				 taskInstanceEntityList.add(taskInstanceEntity);
			 }
			 y++;
		 }
		 if (page == 4){
			 List<TaskInstanceEntity> firstFourElements = taskInstanceEntityList.subList(0, Math.min(taskInstanceEntityList.size(), 4));
			 return Result.OK(firstFourElements);
		 }
		 return Result.OK(taskInstanceEntityList);
	 }
	 /**
	  * 获取我发起的
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/flowable/process/canyuofme")
	 public Result<List<TaskInstanceEntity>> processFlowableCanyuOfMeList(HttpServletRequest req,
																		  @RequestParam(name = "page", defaultValue = "1") int page) {
		 //获取登录用户的ID
		 LoginUser user= (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<HistoricTaskInstance> someoneOngoingTasks = processMethods.getSomeoneParticipateProcess(user.getId());
		 List<TaskInstanceEntity> taskInstanceEntityList = new ArrayList<>();
		 int y = 1;
		 for (int i = 0; i < someoneOngoingTasks.size(); i++) {
			 TaskInstanceEntity taskInstanceEntity = new TaskInstanceEntity();
			 //设置流程实例ID
			 taskInstanceEntity.setProcessInstanceId(someoneOngoingTasks.get(i).getProcessInstanceId());
			 //设置阶段名称
			 taskInstanceEntity.setName(someoneOngoingTasks.get(i).getName());
			 //设置时间
			 taskInstanceEntity.setStartTime(someoneOngoingTasks.get(i).getCreateTime());
			 //设置任务名称
			 QueryWrapper<MonthlySummary> monthlySummaryQueryWrapper = new QueryWrapper<>();
			 monthlySummaryQueryWrapper.eq("act_process_id",someoneOngoingTasks.get(i).getProcessInstanceId());
			 List<MonthlySummary> list = monthlySummaryService.list(monthlySummaryQueryWrapper);
			 if (CollectionUtil.isEmpty(list)){
				 continue;
			 }
			 if (CollectionUtil.isNotEmpty(list)){
				 //操作
				 taskInstanceEntity.setCaozuo("查看");
				 taskInstanceEntity.setXuhao(y);
				 //设置报表名称
				 taskInstanceEntity.setItemName(list.get(0).getReportName());
				 //设置报表ID
				 taskInstanceEntity.setId(list.get(0).getId());
				 //设置阶段名称
				 String progress = list.get(0).getProgress();
				 QueryWrapper<SysDictItem> sysDictItemQueryWrapper = new QueryWrapper<>();
				 sysDictItemQueryWrapper.eq("dict_id","1774975226050961410").eq("item_value",progress);
				 List<SysDictItem> list1 = sysDictItemService.list(sysDictItemQueryWrapper);
				 taskInstanceEntity.setName(list1.get(0).getItemText());
				 //设置状态
				 taskInstanceEntity.setProgress(list.get(0).getProgress());
				 taskInstanceEntityList.add(taskInstanceEntity);
			 }
			 y++;
		 }
		 if (page == 4){
			 List<TaskInstanceEntity> firstFourElements = taskInstanceEntityList.subList(0, Math.min(taskInstanceEntityList.size(), 4));
			 return Result.OK(firstFourElements);
		 }
		 return Result.OK(taskInstanceEntityList);
	 }

	 /**
	  * 流程办理
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/flowable/process/processflowablebanli")
	 public Result<List<TaskInstanceEntity>> processFlowableBanli(TaskInstanceEntity TaskInstanceEntity,HttpServletRequest req) {
		 //获取登录用户的ID
		 LoginUser user= (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 return Result.OK(null);
	 }
	/**
	 *   添加
	 *
	 * @param monthlySummary
	 * @return
	 */
	@Autowired
	private IHywyReportProcessApproveRecordService hywyReportProcessApproveRecordService;
//	 @Autowired
//	 private ISysUserService sysUserService;
	@AutoLog(value = "月度汇总报表-添加")
	@ApiOperation(value="月度汇总报表-添加", notes="月度汇总报表-添加")
	@RequiresPermissions("summary:monthly_summary:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MonthlySummary monthlySummary) {
//		//获取登录用户
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		//获取当前年份和月份
//		// 获取当前日期
//		Date now = new Date();
//		// 设置时间为00:00:00
//		//当前21号00:00:00
//		Date startOfDay = DateUtil.beginOfDay(now);
//		// 格式化年份和月份  2024-04
//		String yearAndMonth = DateUtil.format(startOfDay, "yyyy-MM");
//		// 获取下个月的今天
//		Date nextMonth = DateUtil.offsetMonth(now, 1);
//		// 使用 Calendar 设置为下个月的20号
//		Calendar calendar = DateUtil.calendar(nextMonth);
//		calendar.set(Calendar.DAY_OF_MONTH, 20);
//		// 获取下个月20号的Date对象
//		Date nextMonthTwentieth = calendar.getTime();
//		// 设置时间为23:59:59
//		//下月 20号23:59:59
//		Date endOfDay = DateUtil.endOfDay(nextMonthTwentieth);
//		//获取登录用户的部门信息
//		String loginUserDeptId = getLoginUserDeptId(user.getId());
//		SysDepart depart = departService.getDepartById(loginUserDeptId);
//		//获取部门名称
//		String departName = depart.getDepartName();
//		//设置报表名称
//		String[] split = yearAndMonth.split("-");
//		int i = Integer.parseInt(split[1]);
//		String name = departName+"小区"+split[0]+"年"+i+"月份收入报表";
//		//根据报表名称判断数据库是否有记录
//		QueryWrapper<MonthlySummary> queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("report_name", name);
//		List<MonthlySummary> list = monthlySummaryService.list(queryWrapper);
//		//判断是否有重复数据
//		if (list.size() != 0){
//			return Result.OK("已有数据");
//		}
//		//设置报表名称
//		monthlySummary.setReportName(name);
//		//设置社区ID
//		monthlySummary.setCommunityId(depart.getId());
//		//设置进度
//		monthlySummary.setProgress("0");
//		//设置起止日期
//		monthlySummary.setStartData(startOfDay);
//		monthlySummary.setEndData(endOfDay);
//		//保存汇总表的记录
//		monthlySummaryService.save(monthlySummary);
//
//		//创建审批记录
//		List<MonthlySummary> list2 = monthlySummaryService.list(queryWrapper);
//		//获取汇总表的ID值
//		String id = list2.get(0).getId();
//		//获取汇总的创建人
//		String createBy = list2.get(0).getCreateBy();
//		QueryWrapper<SysUser> queryWrapper2 = new QueryWrapper<>();
//		queryWrapper2.eq("username",createBy);
//		//获取创建人的对象
//		List<SysUser> list1 = sysUserService.list(queryWrapper2);
//		String id1 = list1.get(0).getId();
//		HywyReportProcessApproveRecord hywyReportProcessApproveRecord = new HywyReportProcessApproveRecord();
//		//设置报表名称
//		hywyReportProcessApproveRecord.setBusinessKey(id);
//		//设置审批人
//		hywyReportProcessApproveRecord.setApprover(id1);
//		//设置任务名称
//		hywyReportProcessApproveRecord.setTaskName("物业专员新建");
//		//设置审批结果
//		hywyReportProcessApproveRecord.setApproveResult("Y");
//
//		hywyReportProcessApproveRecordService.save(hywyReportProcessApproveRecord);
		monthlySummaryService.createMonthlySummaryValue();
		return Result.OK("添加成功！");
	}
	 /**
	  * 获取登录用户所在的部门ID
	  *
	  * @return
	  */
	 @Autowired
	 private ISysUserDepartService userDepartService;
	 private String getLoginUserDeptId(String id) {
		 List<DepartIdModel> departIdModels = userDepartService.queryDepartIdsOfUser(id);
		 if (CollectionUtil.isNotEmpty(departIdModels)) {
			 return departIdModels.get(0).getValue();
		 }
		 return null;
	 }

	/**
	 *  报表发起审核  只有物业专员可以发起审核 系统角色授权
	 *
	 * @param monthlySummary
	 * @return
	 */
	@AutoLog(value = "月度汇总报表-编辑")
	@ApiOperation(value="月度汇总报表-编辑", notes="月度汇总报表-编辑")
	@RequiresPermissions("summary:monthly_summary:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> startShenhe(@RequestBody MonthlySummary monthlySummary) {
		//获取登录用户的ID
		LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		//审核新建过滤检查
		if (!monthlySummary.getProgress().equals("0")){
			return Result.OK("只能审核新建状态！");
		}
		//审核本人数据检查
		if (!monthlySummary.getCreateBy().equals(user.getUsername())){
			return Result.OK("只能审核本人数据！");
		}
		//查找当前小区下的物业经理ID
		String nextAplicatonId = monthlySummaryService.selectLocalWyjlId(user.getId());
		//添加判断条件
		if (StrUtil.isEmpty(nextAplicatonId)){
			return Result.OK("当前部门无物业经理！");
		}
		//发起流程 传入业务ID 和 登录用户的ID 返回流程实例Id
		String initiateProcessId = processMethods.initiateProcess(monthlySummary.getId(), user.getId());
		//发起成功后并完成第一个任务
		//设置流程实例ID
		monthlySummary.setActProcessId(initiateProcessId);
		//完成此任务 并传下个任务的审核人
		processMethods.completeSomeoneTask(user.getId(),monthlySummary.getActProcessId(),"wuyejingli",nextAplicatonId);
		//修改报表状态
		monthlySummary.setProgress("1");
		//更新报表
		monthlySummaryService.updateById(monthlySummary);
		//添加审核记录
		SysRole roleOfUser = monthlySummaryService.getRoleOfUser(user.getId());
		hywyReportProcessApproveRecordService.addShenheJilu(user,monthlySummary,roleOfUser);
		return Result.OK("审核成功!");
	}

	 /**
	  * 初始化报表 拉取数据
	  */
	 @Autowired
	 private IElectricChargeService electricChargeService;
	 @Autowired
	 private IPreRechargeService preRechargeService;

//	 @RequiresPermissions("summary:monthly_summary:edit")
	 @RequestMapping(value = "/chushihua", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> chuShihua(@RequestBody MonthlySummary monthlySummary) {
		 //判断报表项表是否有数据
		 QueryWrapper<MonthlySummaryItem> monthlySummaryItemQueryWrapper = new QueryWrapper<>();
		 monthlySummaryItemQueryWrapper.eq("account_period_id",monthlySummary.getId());
		 List<MonthlySummaryItem> monthlySummaryItemList = monthlySummaryItemService.list(monthlySummaryItemQueryWrapper);
		 if (CollectionUtil.isNotEmpty(monthlySummaryItemList)){
			 monthlySummaryItemService.remove(monthlySummaryItemQueryWrapper);
		 }
		 //判断电费表中是否有数据
		 QueryWrapper<ElectricCharge> electricChargeQueryWrapper = new QueryWrapper<>();
		 electricChargeQueryWrapper.eq("zhang_id",monthlySummary.getId());
		 List<ElectricCharge> electricChargeList = electricChargeService.list(electricChargeQueryWrapper);
		 if (CollectionUtil.isNotEmpty(electricChargeList)){
			 electricChargeService.remove(electricChargeQueryWrapper);
		 }
		 //判断充值费用是否有数据
		 QueryWrapper<PreRecharge> preRechargeQueryWrapper = new QueryWrapper<>();
		 preRechargeQueryWrapper.eq("zhang_id",monthlySummary.getId());
		 List<PreRecharge> preRechargeList = preRechargeService.list(preRechargeQueryWrapper);
		 if (CollectionUtil.isNotEmpty(preRechargeList)){
			 preRechargeService.remove(preRechargeQueryWrapper);
		 }
		 //判断装修保证金是否有数据

		 //拉取数据
		 monthlySummaryService.pullShujv(monthlySummary);
		 return Result.OK("初始化成功");
	 }

	 /**
	  * 计算数据
	  * @param monthlySummary
	  * @return
	  */
	 @RequestMapping(value = "/calculatereportitems", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> calculateReportItems(@RequestBody MonthlySummary monthlySummary) {
		 //判断是否有数据
		 QueryWrapper<MonthlySummaryItem> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("account_period_id",monthlySummary.getId());
		 List<MonthlySummaryItem> monthlySummaryItemList = monthlySummaryItemService.list(queryWrapper);
		 QueryWrapper<MonthlySummary> monthlySummaryQueryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("id",monthlySummary.getId());
		 List<MonthlySummary> monthlySummaryList = monthlySummaryService.list(monthlySummaryQueryWrapper);
		 //判断是否有该报表
		 if (monthlySummaryList.isEmpty()){
			 return Result.OK("没有当前报表的数据");
		 }
		 //判断报表项的数据是否为空
		 if (CollectionUtil.isNotEmpty(monthlySummaryItemList)){
			 //清空数据 汇总项
			 monthlySummaryItemService.removeBatchByIds(monthlySummaryItemList);
			 //计算数据
		 }
		 monthlySummaryService.computedShujv(monthlySummary);
		 return Result.OK("计算完成");
	 }

	 /**
	  * 集团会计推送
	  * @param monthlySummaryList
	  * @return
	  */
	 @RequestMapping(value = "/tuisong", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> tuisong(@RequestBody List<MonthlySummary> monthlySummaryList) {
		 //获取登录用户
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 //根据用户ID得到角色code
		 SysRole roleOfUser = monthlySummaryService.getRoleOfUser(user.getId());
		 String roleCode = roleOfUser.getRoleCode();
		 //集团会计的处理逻辑
		 //判断是否处于集团会计审核中
		 for (MonthlySummary monthlySummary : monthlySummaryList) {
			 if (!monthlySummary.getProgress().equals("5")){
				 return Result.error("有未处于集团会计推送的报表！");
			 }
		 }
		 for (MonthlySummary monthlySummary : monthlySummaryList) {
			 if (StrUtil.isNotEmpty(monthlySummary.getActProcessId())){
				 //如果为集团会计 则直接进行通过
				 processMethods.completeSomeoneTask001(user.getId(),monthlySummary.getActProcessId());
			 }
			 //修改报表状态
			 monthlySummary.setProgress("6");
			 //更新报表
			 //重新获取是因为在流程首页 点击办理时 传过来的monsummity对象属性不全 需要查出来覆盖一下
			 QueryWrapper<MonthlySummary> monthlySummaryQueryWrapper = new QueryWrapper<>();
			 monthlySummaryQueryWrapper.eq("id",monthlySummary.getId());
			 List<MonthlySummary> summaryList = monthlySummaryService.list(monthlySummaryQueryWrapper);
			 MonthlySummary monthlySummary1 = summaryList.get(0);
			 monthlySummary1.setProgress(monthlySummary.getProgress());
			 monthlySummary1.setPass(monthlySummary.getPass());
			 //设置备注
			 monthlySummary1.setRemark(monthlySummary.getRemark());
			 monthlySummaryService.updateById(monthlySummary1);
			 //添加审核记录
			 hywyReportProcessApproveRecordService.addShenheJilu3(user,monthlySummary1,roleOfUser);
			 return Result.OK("推送完成！");
		 }

		 return null;
	 }
	 /**
	  * 物业经理 以上发起审核
	  * @param monthlySummary
	  * @return
	  */
	 @RequestMapping(value = "/wuyeshenhe", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> wuyeJingLiShenhe(@Valid @RequestBody MonthlySummary monthlySummary, BindingResult bindingResult) {
		 if (bindingResult.hasErrors()){
			 return Result.error((bindingResult.getFieldError().getDefaultMessage()));
		 }
		 //非业务参数校验
		 if (StrUtil.equals(monthlySummary.getPass(),"N")){
			 if (StrUtil.isEmpty(monthlySummary.getRemark())){
				 return Result.OK("不通过时备注必填！");
			 }
		 }
		 //判断流程ID的任务是否存在
		 Task task = processMethods.checkTaskById(monthlySummary.getActProcessId());
		 if (ObjUtil.isNull(task)){
			 return Result.error("暂未查询到任务！");
		 }
		 //判断是否是我的任务
		 //获取登录用户
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 if (!StrUtil.equals(user.getId(),task.getAssignee())){
			 return Result.error("不是我的任务！");
		 }
		 //获取报表
		 MonthlySummary monthlySummaryItem = monthlySummaryService.getMonthlySummary(monthlySummary);
		 //进行审核
		 return monthlySummaryService.shenheTable(monthlySummaryItem,user);
	 }



	 /**
	  * 取消审核
	  * @param monthlySummary
	  * @return
	  */
	 //注入流程服务
	 @Autowired
	 private IProcessMethods processMethods;
	 @RequestMapping(value = "/quxiaoshenhe", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> quxiaoShenhe(@RequestBody MonthlySummary monthlySummary) {
		 //获取登录用户的ID
		 LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 SysRole roleOfUser = monthlySummaryService.getRoleOfUser(user.getId());
		 //只可以取消本人
		 if (!monthlySummary.getCreateBy().equals(user.getUsername())){
			 return Result.OK("只可以取消本人的报表");
		 }
		 if (monthlySummary.getProgress().equals("0")){
			 return Result.OK("不可以取消新建的！");
		 }
		 //取消流程
		 //如果是已推送就不取消流程 只设置进度
		 if (!monthlySummary.getProgress().equals("6")){
			 processMethods.cancelProcess(monthlySummary.getActProcessId());
		 }
		 //设置为新建
		 monthlySummary.setProgress("0");
		 //充值流程实例ID
		 monthlySummary.setActProcessId(null);
		 //更新报表进度
		 monthlySummaryService.updateById(monthlySummary);
		 //添加审核记录
		 hywyReportProcessApproveRecordService.addShenheJilu4(user,monthlySummary,roleOfUser);
		 return Result.OK("取消成功");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "月度汇总报表-通过id删除")
	@ApiOperation(value="月度汇总报表-通过id删除", notes="月度汇总报表-通过id删除")
	@RequiresPermissions("summary:monthly_summary:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		monthlySummaryService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "月度汇总报表-批量删除")
	@ApiOperation(value="月度汇总报表-批量删除", notes="月度汇总报表-批量删除")
	@RequiresPermissions("summary:monthly_summary:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.monthlySummaryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "月度汇总报表-通过id查询")
	@ApiOperation(value="月度汇总报表-通过id查询", notes="月度汇总报表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MonthlySummary> queryById(@RequestParam(name="id",required=true) String id) {
		MonthlySummary monthlySummary = monthlySummaryService.getById(id);
		if(monthlySummary==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(monthlySummary);
	}

    /**
    * 导出excel
    *
    * @param
    * @param monthlySummary
    */
    @RequiresPermissions("summary:monthly_summary:exportXls")
//    @RequestMapping(value = "/exportXls")
	@PostMapping(value = "/exportXls")
    public ModelAndView exportXls(@RequestBody MonthlySummary monthlySummary) throws IOException {
		//报表项服务
		QueryWrapper<MonthlySummaryItem> monthlySummaryItemQueryWrapper = new QueryWrapper<>();
		monthlySummaryItemQueryWrapper.eq("account_period_id",monthlySummary.getActProcessId());
		List<MonthlySummaryItem> monthlySummaryItemList = monthlySummaryItemService.list(monthlySummaryItemQueryWrapper);
//		MonthlyFinancialStatements incomeReport = service.getById(accountPeriodId);
//		Assert.notNull(incomeReport, "账期记录不存在，请确认！");
		Map<String, Object> templateParamMap = MapUtil.newHashMap();
//		templateParamMap.put("reportName", incomeReport.getReportName());
		templateParamMap.put("reportName", monthlySummary.getReportName());
//		// 获取收入报表项
		TemplateExportParams params = new TemplateExportParams(
				"C:\\Users\\Administrator\\Desktop\\template.xls");  // 模板路径
		templateParamMap.put("items", monthlySummaryItemList);
		Workbook workbook = ExcelExportUtil.exportExcel(params, templateParamMap);

		File savefile = new File("D:\\JAVA\\poi");
		if (!savefile.exists()) {
			savefile.mkdirs();
		}
		FileOutputStream fos = new FileOutputStream("D:\\JAVA\\poi\\result.xlsx");
		workbook.write(fos);
		fos.close();
		// 将Workbook转换为byte数组
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效 ,前端会重更新设置一下
//		mv.addObject(NormalExcelConstants.FILE_NAME, title);
//		mv.addObject(NormalExcelConstants.CLASS, clazz);
//		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
//		ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
//		exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload());
//		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
//		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
//		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("summary:monthly_summary:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MonthlySummary.class);
    }

}
